package org.odst.transformer;

import java.util.ArrayList;
import java.util.List;

import org.odst.controller.SheetTransformationController;
import org.odst.parser.Cell;
import org.odst.processor.CellProcessor;
import org.odst.transformation.ResultTransformation;


/**
 * @author Leonid Vysochyn
 * @author Cyril PODER
 */
public class SimpleRowTransformer extends BaseRowTransformer {

    Configuration configuration;
    List<CellProcessor> cellProcessors;
    List<Cell> cells = new ArrayList<Cell>();

    private ResultTransformation resultTransformation;

    public SimpleRowTransformer(Row row, List<CellProcessor> cellProcessors, Configuration configuration) {
        this.row = row;
        this.cellProcessors = cellProcessors;
        this.configuration = configuration;
    }

    public void addCell(Cell cell){
        if( !cell.isEmpty() ){
            cells.add( cell );
        }
    }

    public ResultTransformation getTransformationResult() {
        return resultTransformation;
    }

    public List<Cell> getCells() {
        return cells;
    }


    public ResultTransformation transform(SheetTransformationController stc, SheetTransformer sheetTransformer/*, ResultTransformation previousTransformation*/){
        CellTransformer cellTransformer = new CellTransformer( configuration );
        int rowIndex = row.getRowIndex();
        if( cells.isEmpty() ){
//            throw new RuntimeException("Don't expect to execute this code");
            for (Cell cell : row.getCells()) {
                applyCellProcessors(row.getSheet(), cell );
                cellTransformer.transform( rowIndex, cell );
            }
        }else{
            for (Cell cell : cells) {
//                if( previousTransformation != null && cell.getOooCell().getColumnIndex()>= previousTransformation.getStartCellShift()
//                        && previousTransformation.getStartCellShift() != 0){
//                    cell.replaceCellWithNewShiftedBy(previousTransformation.getLastCellShift());
//                }
                applyCellProcessors( row.getSheet(), cell );
                cellTransformer.transform( rowIndex, cell );
            }
        }
        resultTransformation = new ResultTransformation();
        return resultTransformation;
    }

    /**
     * Applies all registered CellProcessors to a cell
     * @param sheet - {@link Sheet} to apply Cell Processors to
     * @param cell - {@link org.odst.parser.Cell} object with cell information
     */
    private void applyCellProcessors(Sheet sheet, Cell cell) {
        for (CellProcessor cellProcessor : cellProcessors) {
            cellProcessor.processCell(cell, sheet.getNamedCells());
        }
    }




}
